package com.ybk.zs.controller;

import com.ybk.zs.common.utils.StringUtils;
import com.ybk.zs.controller.resp.BaseResp;
import com.ybk.zs.controller.resp.LoginResp;
import com.ybk.zs.domain.Admin;
import com.ybk.zs.domain.AdminExample;
import com.ybk.zs.interceptors.TokenProcessor;
import com.ybk.zs.service.IAdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * 登录
 * Created by duanjixing on 2016/8/30.
 */
@Controller
//@CrossOrigin
@RequestMapping(value = "/login/")
public class LoginController {

    @Autowired
    IAdminService adminService;

    @RequestMapping(value = "adminLogin" ,method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public LoginResp adminLogin(HttpServletRequest request, HttpServletResponse response,String name, String password){

        LoginResp resp = new LoginResp();
        if(StringUtils.isBlank(name)){
            resp.setResultCode("002");
            resp.setResultMsg("name is null");
            return resp;
        }else if(StringUtils.isBlank(password)){
            resp.setResultCode("002");
            resp.setResultMsg("密码为空");
            return resp;
        }

        AdminExample example = new AdminExample();
        example.or().andNameEqualTo(name);
        List<Admin> list = adminService.selectByExample(example);

        if(list!=null&&list.size()>0){
            Admin admin = list.get(0);

            if(admin.getPassword().equals(password)){
                HttpSession session = request.getSession();
                String token = new TokenProcessor().generateToken(name, true);
                session.setAttribute("token",token);
                admin.setPassword("");
                resp.setAdmin(admin);
                resp.setToken(token);
                resp.setResultCode("001");
                resp.setResultMsg("登录成功");
                return resp;
            }else {
                resp.setResultCode("002");
                resp.setResultMsg("用户名或密码错误");
                return resp;
            }
        }else {
            resp.setResultCode("002");
            resp.setResultMsg("admin do not exists");
            return resp;
        }
    }
}
